package com.xjh.basestudy.javabase.thread_final.aqs;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author:XuJianHua
 * @Date:2022/10/28
 * @Description:
 * ABC 执行的先后顺序可能不一样
 * 无论什么样的结果，num最终的值总是1600，这说明我们加锁是成功的。
 */
public class AQSDemo {

  private static int num;


  public static void main(String[] args) {

    ReentrantLock lock = new ReentrantLock();

    new Thread(new Runnable() {
      @Override
      public void run() {
        lock.lock();
        try {
          Thread.sleep(1000);
          num += 1000;
          System.out.println("A 线程执行了1秒,num = " + num);
        } catch (InterruptedException e) {
          e.printStackTrace();
        } finally {
          lock.unlock();
        }
      }
    }, "A").start();

    new Thread(new Runnable() {
      @Override
      public void run() {
        lock.lock();
        try {
          Thread.sleep(500);
          num += 500;
          System.out.println("B 线程执行了0.5秒,num = " + num);
        } catch (InterruptedException e) {
          e.printStackTrace();
        } finally {
          lock.unlock();
        }
      }
    }, "B").start();

    new Thread(new Runnable() {
      @Override
      public void run() {
        lock.lock();
        try {
          Thread.sleep(100);
          num += 100;
          System.out.println("C 线程执行了0.1秒,num = " + num);
        } catch (InterruptedException e) {
          e.printStackTrace();
        } finally {
          lock.unlock();
        }
      }
    }, "C").start();
  }


}
